package com.wow.wa.bill.serivce;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.util.Log;

import com.wow.wa.bill.serivce.vo.ShareBean;

public class CollectDateCompentImpl implements CollectDateCompent {

	private static final String TAG = CollectDateCompentImpl.class.getName();
	private transient Context context;

	public CollectDateCompentImpl(Context context) {
		this.context = context;
	}

	public Context getContext() {
		return context;
	}

	@Override
	public ShareBean readData() {

		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this.context);

		final ShareBean bean = new ShareBean();
		Field[] fs = bean.getClass().getDeclaredFields();

		try {

			for (Field f : fs) {

				if (Modifier.isStatic(f.getModifiers())) {
					continue;
				}

				f.setAccessible(true);

				Class<?> pClass = f.getType();
				if (pClass == Boolean.class || pClass == boolean.class) {
					f.set(bean, prefs.getBoolean(f.getName(), false));
				} else if (pClass == String.class) {
					f.set(bean, prefs.getString(f.getName(), StringUtils.EMPTY));
				} else if (pClass == Integer.class || pClass == int.class) {
					f.set(bean, prefs.getInt(f.getName(), -1));
				} else if (pClass == Long.class || pClass == long.class) {
					f.set(bean, prefs.getLong(f.getName(), -1));
				}
				f.setAccessible(false);

			}

		} catch (Exception e) {
			Log.v(TAG, "");
		}
		return bean;
	}

	@Override
	public void edit(ShareBean bena) {

		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this.context);

		final Editor edit = prefs.edit();

		final ShareBean bean = new ShareBean();

		final Field[] fs = bean.getClass().getFields();

		try {

			for (Field f : fs) {

				final Object objValue = BeanUtils
						.getProperty(bean, f.getName());

				Class<?> pClass = f.getType();

				if (pClass == Boolean.class || pClass == boolean.class) {
					edit.putBoolean(f.getName(), (Boolean) objValue);
				} else if (pClass == String.class) {
					edit.putString(f.getName(), (String) objValue);
				} else if (pClass == Integer.class || pClass == int.class) {
					edit.putInt(f.getName(), (Integer) objValue);
				} else if (pClass == Long.class || pClass == long.class) {
					edit.putLong(f.getName(), (Long) objValue);
				}

			}
			edit.commit();

		} catch (Exception e) {
			Log.v(TAG, "edit error=" + e.getMessage());
		}

	}
}
